package com.itheima.exception;

import java.util.Scanner;

public class ExceptionDemo2 {
    public static void main(String[] args) {

        Student s = new Student();
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入姓名");
        String name = sc.next();
        s.setName(name);

        while(true){
            System.out.println("请输入年龄");
            String ageStr = sc.next();
            try {
                int age = Integer.parseInt(ageStr);
                s.setAge(age);
                break;
            }catch (NumberFormatException n){
                System.out.println("请输入整数");
            }catch (AgeOutOfBoundException r){
                r.printStackTrace();
                System.out.println("请输入范围内的年龄");
            }
        }
        System.out.println(s);
    }
}
class Student{
    private String name;
    private int age;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) throws AgeOutOfBoundException {
        if(age >=18 && age <= 25) {
            this.age = age;
        }else{
            throw new AgeOutOfBoundException("年龄超出了范围");
        }
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
class AgeOutOfBoundException extends RuntimeException{
    public AgeOutOfBoundException() {
    }

    public AgeOutOfBoundException(String message) {
        super(message);
    }
}